package com.rc.evcharger.dto.terminal;

import com.rc.evcharger.common.annotation.ByteLength;
import com.rc.evcharger.common.terminal.Result;
import com.rc.evcharger.common.utils.StringUtil;

import java.lang.reflect.Field;

/**
 * Create by Yang on 2019/11/5
 */
public class CardNoResult implements Result {

    @ByteLength(length = 14)
    private String cardNo;  //卡号

    @ByteLength(length = 1)
    private String gunNum;  //枪号

    @ByteLength(length = 1)
    private String status;  //00/01 启动  02停止

    @ByteLength(length = 3)
    private String obligate; //预留字段;

    public String getCardNo() {
        return cardNo;
    }

    public void setCardNo(String cardNo) {
        this.cardNo = cardNo;
    }

    public String getGunNum() {
        return gunNum;
    }

    public void setGunNum(String gunNum) {
        this.gunNum = gunNum;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getObligate() {
        return obligate;
    }

    public void setObligate(String obligate) {
        this.obligate = obligate;
    }

    /**
     * 遍历所有字段，按顺序和长度截取数据
     *
     * @param str    数据域
     */
    public CardNoResult(String str) {
        try {
            Field[] fields = this.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                ByteLength bl = fields[i].getAnnotation(ByteLength.class);
                if (bl == null) {
                    continue;
                }
                int len = bl.length() * 2 + bl.length() - 1;
                String value = str.substring(0, len);
                if (str.length() > len) {
                    str = str.substring(len + 1);
                }
                setValue(fields[i], bl, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public CardNoResult() {
    }

    private void setValue(Field field, ByteLength bl, String value) {
        try {
            if ((field.getName().equals("cardNo"))) {
                field.set(this, StringUtil.resolveVin(value));
            } else {
                field.set(this, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public CardNoResult getResult(String dataStr) {
        CardNoResult cardNoResult = new CardNoResult(dataStr);
        return cardNoResult;
    }

    public static void main(String[] args) {
        //68 62 97 44 00 02 61 00 00 68 A3 13 00 36 35 30 30 30 30 30 30 30 30 30 30 30 31 01 01 00 00 00 C9 16
        CardNoResult cardNoResult = new CardNoResult();
        CardNoResult result = cardNoResult.getResult("36 35 30 30 30 30 30 30 30 30 30 30 30 31 01 01 00 00 00");
        System.out.println(result.toString());
    }
}
